<template>
  <div class="container-fluid p-4">
    <!-- 考试中界面 -->
    <div id="exam-during" class="row">
      <div class="col-12 mb-3">
        <el-card class="border-0 shadow-sm">
          <div
            class="card-body d-flex justify-content-between align-items-center py-2"
          >
            <div>
              <h5 class="mb-0">静脉输液技术规范期末考核</h5>
            </div>
            <div class="timer-display" id="exam-timer">
              剩余时间: {{ timerDisplay }}
            </div>
          </div>
        </el-card>
      </div>
      <div class="col-md-9 mb-4">
        <el-card class="border-0 shadow-sm">
          <div class="card-body">
            <div id="question-container">
              <!-- 题目内容将通过Vue动态渲染 -->
              <div class="mb-4">
                <div class="d-flex justify-content-between mb-3">
                  <h5>
                    第 {{ currentQuestion.id }} 题
                    {{ questionTypeText(currentQuestion.type) }}
                  </h5>
                  <el-badge :type="questionBadgeType(currentQuestion.type)"
                    >{{ questionTypeText(currentQuestion.type) }}
                  </el-badge>
                </div>
                <div class="question-content mb-4">
                  {{ currentQuestion.content }}
                </div>
              </div>

              <div
                class="mb-4"
                v-if="
                  currentQuestion.type === 'single' ||
                  currentQuestion.type === 'multiple'
                "
              >
                <div
                  class="form-check mb-2"
                  v-for="option in currentQuestion.options"
                  :key="option.id"
                >
                  <input
                    class="form-check-input"
                    :type="
                      currentQuestion.type === 'single' ? 'radio' : 'checkbox'
                    "
                    :name="`question-${currentQuestion.id}`"
                    :id="`option-${currentQuestion.id}-${option.id}`"
                    :value="option.id"
                    v-model="currentQuestion.answer"
                  />
                  <label
                    class="form-check-label"
                    :for="`option-${currentQuestion.id}-${option.id}`"
                  >
                    {{ option.id }}. {{ option.text }}
                  </label>
                </div>
              </div>

              <div class="mb-4" v-else-if="currentQuestion.type === 'essay'">
                <textarea
                  class="form-control"
                  :id="`essay-answer-${currentQuestion.id}`"
                  rows="6"
                  placeholder="请在此输入您的答案..."
                  v-model="currentQuestion.answer"
                ></textarea>
              </div>
            </div>
            <div class="d-flex justify-content-between mt-4">
              <el-button
                id="prev-question"
                class="btn btn-outline-secondary"
                @click="prevQuestion"
                :disabled="currentQuestionIndex === 0"
              >
                <i class="bi bi-arrow-left me-2"></i>上一题
              </el-button>
              <div>
                <el-button
                  id="report-error"
                  class="btn btn-outline-danger me-2"
                  @click="showErrorReportModal"
                >
                  <i class="bi bi-exclamation-circle me-2"></i>报错
                </el-button>
                <el-button
                  id="submit-exam"
                  class="btn btn-primary"
                  @click="submitExam"
                >
                  <i class="bi bi-check-circle me-2"></i>提交考试
                </el-button>
              </div>
              <el-button
                id="next-question"
                class="btn btn-outline-primary"
                @click="nextQuestion"
                :disabled="
                  currentQuestionIndex === examData.questions.length - 1
                "
              >
                下一题<i class="bi bi-arrow-right ms-2"></i>
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
      <div class="col-md-3 mb-4">
        <el-card class="border-0 shadow-sm">
          <template #header>
            <div class="card-header bg-white py-3">
              <h5 class="mb-0">题目导航</h5>
            </div>
          </template>
          <div class="card-body">
            <div class="mb-3">
              <div class="d-flex align-items-center mb-2">
                <div class="question-nav-item me-2 active"></div>
                <span>当前题目</span>
              </div>
              <div class="d-flex align-items-center mb-2">
                <div class="question-nav-item me-2 answered"></div>
                <span>已答题目</span>
              </div>
              <div class="d-flex align-items-center">
                <div class="question-nav-item me-2"></div>
                <span>未答题目</span>
              </div>
            </div>
            <div class="mb-3">
              <h6 class="mb-2">单选题 (1-15)</h6>
              <div class="d-flex flex-wrap">
                <div
                  class="question-nav-item"
                  :class="{
                    active: index === currentQuestionIndex,
                    answered: answeredQuestions.has(index),
                  }"
                  v-for="(question, index) in singleChoiceQuestions"
                  :key="index"
                  @click="navigateToQuestion(index)"
                >
                  {{ question.id }}
                </div>
              </div>
            </div>
            <div class="mb-3">
              <h6 class="mb-2">多选题 (16-25)</h6>
              <div class="d-flex flex-wrap">
                <div
                  class="question-nav-item"
                  :class="{
                    active: index === currentQuestionIndex,
                    answered: answeredQuestions.has(index),
                  }"
                  v-for="(question, index) in multipleChoiceQuestions"
                  :key="index + 15"
                  @click="navigateToQuestion(index + 15)"
                >
                  {{ question.id }}
                </div>
              </div>
            </div>
            <div class="mb-3">
              <h6 class="mb-2">简答题 (26-30)</h6>
              <div class="d-flex flex-wrap">
                <div
                  class="question-nav-item"
                  :class="{
                    active: index === currentQuestionIndex,
                    answered: answeredQuestions.has(index),
                  }"
                  v-for="(question, index) in essayQuestions"
                  :key="index + 25"
                  @click="navigateToQuestion(index + 25)"
                >
                  {{ question.id }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <error-report-modal
      v-model="modalController.popups.errorReportModal"
    ></error-report-modal>
    <submit-confirm-modal
      v-model="modalController.popups.submitConfirmModal"
    ></submit-confirm-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, watch } from "vue";
import { ElMessage } from "element-plus";
import SubmitConfirmModal from "@/components/alert/exam/SubmitConfirmModal.vue";
import ErrorReportModal from "@/components/alert/exam/ErrorReportModal.vue";
import { modalControllers } from "@/stores/modalController.js";

const modalController = modalControllers();
// 考试数据
const examData = {
  questions: [
    // 单选题示例
    {
      id: 1,
      type: "single",
      content: "静脉输液时，调节滴速的正确方法是：",
      options: [
        { id: "A", text: "调节输液器上的滚轮" },
        { id: "B", text: "调节输液瓶的高度" },
        { id: "C", text: "更换不同型号的输液器" },
        { id: "D", text: "调整患者的体位" },
      ],
      answer: null,
    },
    {
      id: 2,
      type: "single",
      content: "下列哪项不是静脉输液前的准备工作：",
      options: [
        { id: "A", text: "核对医嘱" },
        { id: "B", text: "准备输液器具" },
        { id: "C", text: "向患者解释" },
        { id: "D", text: "测量血压" },
      ],
      answer: null,
    },
    // 多选题示例
    {
      id: 16,
      type: "multiple",
      content: "静脉输液过程中可能出现的并发症包括：",
      options: [
        { id: "A", text: "液体外渗" },
        { id: "B", text: "空气栓塞" },
        { id: "C", text: "发热反应" },
        { id: "D", text: "过敏反应" },
        { id: "E", text: "血栓形成" },
      ],
      answer: [],
    },
    {
      id: 17,
      type: "multiple",
      content: "下列哪些因素会影响静脉输液的滴速：",
      options: [
        { id: "A", text: "输液瓶高度" },
        { id: "B", text: "患者体位" },
        { id: "C", text: "输液管路长度" },
        { id: "D", text: "室内温度" },
      ],
      answer: [],
    },
    // 简答题示例
    {
      id: 26,
      type: "essay",
      content: "请简述静脉输液的操作步骤和注意事项。",
      answer: "",
    },
    {
      id: 27,
      type: "essay",
      content: "静脉输液过程中出现液体外渗时，应如何处理？",
      answer: "",
    },
  ],
};
// 当前题目索引
const currentQuestionIndex = ref(0);
// 考试剩余时间（秒）
const remainingTime = ref(60 * 60);
// 计时器
const timerInterval = ref(null);
// 答题记录
const answeredQuestions = new Set();

// 获取当前题目
const currentQuestion = computed(() => {
  return examData.questions[currentQuestionIndex.value] || {};
});

// 单选题
const singleChoiceQuestions = computed(() => {
  return examData.questions.filter((q) => q.type === "single");
});

// 多选题
const multipleChoiceQuestions = computed(() => {
  return examData.questions.filter((q) => q.type === "multiple");
});

// 简答题
const essayQuestions = computed(() => {
  return examData.questions.filter((q) => q.type === "essay");
});

// 已答题目数量
const answeredCount = computed(() => {
  return Array.from(answeredQuestions).filter(
    (index) => index < examData.questions.length,
  ).length;
});

// 未答题目数量
const unansweredCount = computed(() => {
  return examData.questions.length - answeredCount.value;
});

// 计时器显示
const timerDisplay = computed(() => {
  const minutes = Math.floor(remainingTime.value / 60);
  const seconds = remainingTime.value % 60;
  return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
});

// 错误报告相关
const errorReportVisible = ref(false);
const errorType = ref("");
const errorDescription = ref("");

// 提交确认相关
const submitConfirmVisible = ref(false);

// 导航到指定题目
function navigateToQuestion(index) {
  if (index >= 0 && index < examData.questions.length) {
    currentQuestionIndex.value = index;
    updateQuestionNav();
  }
}

// 获取题目类型文本
function questionTypeText(type) {
  switch (type) {
    case "single":
      return "单选题";
    case "multiple":
      return "多选题";
    case "essay":
      return "简答题";
    default:
      return "";
  }
}

// 获取题目类型徽章样式
function questionBadgeType(type) {
  switch (type) {
    case "single":
      return "primary";
    case "multiple":
      return "info";
    case "essay":
      return "warning";
    default:
      return "secondary";
  }
}

// 更新计时器显示
function updateTimer() {
  remainingTime.value--;

  // 时间少于5分钟时显示警告
  if (remainingTime.value <= 300) {
    // 可以添加警告样式
  }

  // 时间到自动提交
  if (remainingTime.value <= 0) {
    clearInterval(timerInterval.value);
    submitExam();
  }
}

// 开始考试
function startExam() {
  // 初始化题目导航
  // initQuestionNav();

  // 启动计时器
  timerInterval.value = setInterval(updateTimer, 1000);
}

// 确认提交考试
function confirmSubmit() {
  // 这里可以添加提交考试的逻辑
  ElMessage.success({
    message: "考试已提交！",
    duration: 2000,
  });
  setTimeout(() => {
    // window.location.href = 'assessment.html'; // 提交后返回考核评估页面
  }, 2000);
}

// 显示报错模态框
function showErrorReportModal() {
  errorReportVisible.value = true;
  modalController.openPopup("errorReportModal");
}

// 上一题
function prevQuestion() {
  if (currentQuestionIndex.value > 0) {
    navigateToQuestion(currentQuestionIndex.value - 1);
  }
}

// 下一题
function nextQuestion() {
  if (currentQuestionIndex.value < examData.questions.length - 1) {
    navigateToQuestion(currentQuestionIndex.value + 1);
  }
}

// 监听答题变化
onMounted(() => {
  // 侧边栏切换
  document
    .getElementById("sidebarToggle")
    ?.addEventListener("click", function (e) {
      e.preventDefault();
      document.getElementById("wrapper").classList.toggle("toggled");
    });

  // 开始考试按钮事件监听
  const startExamBtn = document.getElementById("start-exam-btn");
  if (startExamBtn) {
    startExamBtn.addEventListener("click", () => {
      startExam();
    });
  }

  // 初始化题目导航
  initQuestionNav();

  // 渲染当前题目
  renderCurrentQuestion();
});

// 销毁前清理
onBeforeUnmount(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
  }
});

// 初始化题目导航
function initQuestionNav() {
  const questionNav = document.getElementById("question-nav");
  if (questionNav) {
    // 动态生成题目导航项
    examData.questions.forEach((question, index) => {
      const navItem = document.createElement("div");
      navItem.className = "question-nav-item";
      navItem.textContent = question.id;
      navItem.addEventListener("click", () => navigateToQuestion(index));
      questionNav.appendChild(navItem);
    });
  }
}

// 更新题目导航状态
function updateQuestionNav() {
  const navItems = document.querySelectorAll(".question-nav-item");
  navItems.forEach((item, index) => {
    item.classList.remove("active", "answered");
    if (index === currentQuestionIndex.value) {
      item.classList.add("active");
    }
    if (answeredQuestions.has(index)) {
      item.classList.add("answered");
    }
  });
}

// 渲染当前题目
function renderCurrentQuestion() {
  const questionContainer = document.getElementById("question-container");
  if (questionContainer && currentQuestion.value) {
    questionContainer.innerHTML = `<!-- 题目内容动态渲染 -->
      <div class="mb-4">
        <div class="d-flex justify-content-between mb-3">
          <h5>第 ${currentQuestion.value.id} 题 ${questionTypeText(currentQuestion.value.type)}</h5>
          <el-badge :type="questionBadgeType(currentQuestion.value.type)">${questionTypeText(currentQuestion.value.type)}</el-badge>
        </div>
        <div class="question-content mb-4">${currentQuestion.value.content}</div>
      </div>`;

    // 根据题目类型渲染不同的答题区域
    if (
      currentQuestion.value.type === "single" ||
      currentQuestion.value.type === "multiple"
    ) {
      let optionsHTML = "";
      currentQuestion.value.options.forEach((option) => {
        optionsHTML += `
        <div class="form-check mb-2">
          <input class="form-check-input"
                 type="${currentQuestion.value.type === "single" ? "radio" : "checkbox"}"
                 name="question-${currentQuestion.value.id}"
                 id="option-${currentQuestion.value.id}-${option.id}"
                 value="${option.id}"/>
          <label class="form-check-label" for="option-${currentQuestion.value.id}-${option.id}">
            ${option.id}. ${option.text}
          </label>
        </div>`;
      });

      questionContainer.innerHTML += `
      <div class="mb-4">
        ${optionsHTML}
      </div>`;
    } else if (currentQuestion.value.type === "essay") {
      questionContainer.innerHTML += `
      <div class="mb-4">
        <textarea class="form-control"
                  id="essay-answer-${currentQuestion.value.id}"
                  rows="6"
                  placeholder="请在此输入您的答案..."></textarea>
      </div>`;
    }

    // 添加题号点击事件
    examData.questions.forEach((_, index) => {
      const navItem = document.querySelector(
        `.question-nav-item[data-index="${index}"]`,
      );
      if (navItem) {
        navItem.addEventListener("click", () => navigateToQuestion(index));
      }
    });
  }
}

// 答题记录更新
function recordAnswer() {
  const currentAnswer = currentQuestion.value.answer;
  if (currentAnswer !== null && currentAnswer !== "") {
    answeredQuestions.add(currentQuestionIndex.value);
  } else {
    answeredQuestions.delete(currentQuestionIndex.value);
  }
  updateQuestionNav();
}

// 监听答题变化
watch(
  () => currentQuestion.value.answer,
  (newVal) => {
    recordAnswer();
  },
);

// 计算总体进度
function calculateOverallProgress() {
  return (answeredQuestions.size / examData.questions.length) * 100;
}

// 添加窗口卸载事件监听器
window.addEventListener("beforeunload", function (e) {
  if (remainingTime.value > 0) {
    e.preventDefault();
    e.returnValue = "您确定要离开考试页面吗？这可能导致答案丢失。";
  }
});

// 提交考试函数
function submitExam() {
  // 更新统计信息
  modalController.openPopup("submitConfirmModal");
  updateExamStats();
}

// 更新考试统计信息
function updateExamStats() {
  const totalQuestions = examData.questions.length;
  const answeredCount = answeredQuestions.size;
  const unAnsweredCount = totalQuestions - answeredCount;

  document.getElementById("total-questions").textContent = totalQuestions;
  document.getElementById("answered-count").textContent = answeredCount;
  document.getElementById("unanswered-count").textContent = unAnsweredCount;
}

// 确认提交考试
function confirmSubmitExam() {
  // 这里可以添加实际提交考试的逻辑
  console.log("考试已提交");

  // 隐藏模态框
  SubmitConfirmModal.value = false;

  // 可以在这里添加跳转到考试结果页面的逻辑
  // router.push('/exam/result');
}
</script>
